package org.frvi.goldspring.web.wicket.application;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.frvi.goldspring.business.dao.UserDao;
import org.frvi.goldspring.business.entity.User;
import org.frvi.goldspring.business.service.UserService;

/**
 * User: Frank
 * Date: Oct 15, 2009
 * Time: 11:01:22 PM
 */
public class GoldSpringWebSession extends AuthenticatedWebSession {

    @SpringBean
    UserService userService;
    Principal principal;


    public GoldSpringWebSession(Request request) {
        super(request);
        InjectorHolder.getInjector().inject(this);

    }

    @Override
    public boolean authenticate(String username, String password) {
        User user = userService.findByUserName(username);
        // TODO: password needs to be hashed with sha5
        if (user != null && password.equals(user.getPassword())) {
            principal = new Principal();
            principal.setName(user.getUsername());
            principal.setRoles(new Roles(user.getRoles()));
        }
        return principal != null;
    }

    @Override
    public Roles getRoles() {
        if (isSignedIn()) {
            return principal.getRoles();
        }
        return null;
    }
}
